<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>3D照片展厅</title>
    <style>
        body { 
            margin: 0;
            overflow: hidden;
            font-family: Arial, sans-serif;
            background: #000;
        }
        #container {
            position: absolute;
            width: 100%;
            height: 100%;
        }
        #info {
            position: absolute;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0,0,0,0.7);
            padding: 10px 20px;
            border-radius: 20px;
            color: white;
            z-index: 100;
            max-width: 80%;
            text-align: center;
        }
        #loading {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: white;
            font-size: 18px;
            z-index: 100;
        }
        #back-btn {
            position: absolute;
            top: 20px;
            left: 20px;
            background: rgba(255,255,255,0.2);
            border: none;
            color: white;
            padding: 8px 15px;
            border-radius: 15px;
            cursor: pointer;
            z-index: 100;
        }
    </style>
</head>
<body>
    <div id="container"></div>
    <div id="info">3D照片展厅 - 点击照片查看</div>
    <div id="loading">加载展厅中...</div>
    <button id="back-btn">返回</button>

    <!-- Three.js 库 -->
    <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/controls/OrbitControls.js"></script>
    
    <script>
        // ==================== 初始化 ====================
        const scene = new THREE.Scene();
        scene.background = new THREE.Color(0x111111);
        
        const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        camera.position.z = 15;
        
        const renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.getElementById('container').appendChild(renderer.domElement);
        
        const controls = new THREE.OrbitControls(camera, renderer.domElement);
        controls.enableDamping = true;
        controls.dampingFactor = 0.05;
        
        // 光源
        const ambientLight = new THREE.AmbientLight(0x404040);
        scene.add(ambientLight);
        
        const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
        directionalLight.position.set(1, 1, 1).normalize();
        scene.add(directionalLight);
        
        // 照片组
        const photoGroup = new THREE.Group();
        scene.add(photoGroup);

        // ==================== 照片配置 ====================
        // 从URL参数获取照片数据
        function getPhotoData() {
            // 
            return [
                { url: '../星露谷物语/图片/汉堡.png', title: '1', desc: '' },
                { url: '../星露谷物语/图片/p3.png', title: '2', desc: '' },
                { url: '../星露谷物语/图片/Animals_Icon.png', title: '3', desc: '' },
                { url: '../星露谷物语/图片/Junimo_Icon.png', title: '4', desc: '' }
                // 添加更多照片...
            ];
        }

        // ==================== 图片加载 ====================
        // 创建错误纹理
        function createErrorTexture() {
            const canvas = document.createElement('canvas');
            canvas.width = 512;
            canvas.height = 512;
            const ctx = canvas.getContext('2d');
            ctx.fillStyle = '#ff0000';
            ctx.fillRect(0, 0, 512, 512);
            ctx.fillStyle = '#ffffff';
            ctx.font = '24px Arial';
            ctx.textAlign = 'center';
            ctx.fillText('图片加载失败', 256, 256);
            return new THREE.CanvasTexture(canvas);
        }

        // 增强版加载函数
        async function loadImage(url) {
            return new Promise((resolve, reject) => {
                const img = new Image();
                img.onload = () => resolve(img);
                img.onerror = () => {
                    console.error(`图片加载失败: ${url}`);
                    resolve(createErrorTexture().image);
                };
                
                // 处理路径 - 确保在file://协议下也能工作
                let finalUrl = url;
                if (window.location.protocol === 'file:' && !url.startsWith('./')) {
                    finalUrl = './' + url;
                }
                
                img.src = finalUrl;
            });
        }

        // 加载所有照片
        async function loadAllPhotos() {
            const photos = getPhotoData();
            let loadedCount = 0;
            
            for (const photo of photos) {
                try {
                    const img = await loadImage(photo.url);
                    const texture = new THREE.Texture(img);
                    texture.needsUpdate = true;
                    createPhotoMesh(texture, photo);
                    loadedCount++;
                    updateProgress(loadedCount, photos.length);
                } catch (error) {
                    console.error(`加载照片失败: ${photo.url}`, error);
                    const errorTexture = createErrorTexture();
                    createPhotoMesh(errorTexture, photo);
                }
            }
            
            document.getElementById('loading').style.display = 'none';
            arrangePhotos();
        }

        // 创建照片网格
        function createPhotoMesh(texture, photo) {
            const material = new THREE.MeshBasicMaterial({ 
                map: texture,
                side: THREE.DoubleSide
            });
            
            const geometry = new THREE.PlaneGeometry(3, 2);
            const mesh = new THREE.Mesh(geometry, material);
            
            mesh.userData = photo;
            photoGroup.add(mesh);
            return mesh;
        }

        // 更新加载进度
        function updateProgress(loaded, total) {
            document.getElementById('loading').textContent = `加载中... ${loaded}/${total}`;
        }

        // ==================== 照片布局 ====================
        function arrangePhotos() {
            const count = photoGroup.children.length;
            const radius = 8;
            
            // 球形布局
            photoGroup.children.forEach((photo, i) => {
                const phi = Math.acos(-1 + (2 * i) / count);
                const theta = Math.sqrt(count * Math.PI) * phi;
                
                photo.position.set(
                    radius * Math.cos(theta) * Math.sin(phi),
                    radius * Math.sin(theta) * Math.sin(phi),
                    radius * Math.cos(phi)
                );
                
                // 朝向中心
                photo.lookAt(0, 0, 0);
                
                // 保存原始位置
                photo.userData.originalPosition = photo.position.clone();
                photo.userData.originalRotation = photo.rotation.clone();
            });
            
            setupInteractions();
        }

        // ==================== 交互功能 ====================
        function setupInteractions() {
            const raycaster = new THREE.Raycaster();
            const mouse = new THREE.Vector2();
            let currentPhoto = null;
            
            // 点击事件
            window.addEventListener('click', (event) => {
                mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
                mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
                
                raycaster.setFromCamera(mouse, camera);
                const intersects = raycaster.intersectObjects(photoGroup.children);
                
                if (intersects.length > 0) {
                    const photo = intersects[0].object;
                    focusOnPhoto(photo);
                }
            });
            
            // 返回按钮
            document.getElementById('back-btn').addEventListener('click', () => {
                if (window.history.length > 1) {
                    window.history.back();
                } else {
                    window.location.href = 'index.html'; // 返回主页
                }
            });
        }

        // 聚焦照片
        function focusOnPhoto(photo) {
            // 计算相机位置
            const cameraPosition = photo.position.clone();
            cameraPosition.z += 5;
            
            // 动画相机
            animateCamera(cameraPosition);
            
            // 更新信息
            document.getElementById('info').textContent = 
                `${photo.userData.title} - ${photo.userData.desc}`;
        }

        // 相机动画
        function animateCamera(targetPosition) {
            const duration = 1;
            const startPosition = camera.position.clone();
            const startTime = Date.now();
            
            function update() {
                const elapsed = (Date.now() - startTime) / 1000;
                const progress = Math.min(elapsed / duration, 1);
                
                camera.position.lerpVectors(startPosition, targetPosition, progress);
                
                if (progress < 1) {
                    requestAnimationFrame(update);
                }
            }
            
            update();
        }

        // ==================== 动画循环 ====================
        function animate() {
            requestAnimationFrame(animate);
            controls.update();
            renderer.render(scene, camera);
        }

        // ==================== 窗口调整 ====================
        window.addEventListener('resize', () => {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize(window.innerWidth, window.innerHeight);
        });

        // ==================== 启动 ====================
        loadAllPhotos();
        animate();
    </script>
</body>
</html>